//
//  UUOrderStateListVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 22/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUOrderStateListVC.h"
#import "UUOrderCell.h"
#import "UUOrderManager.h"
#import "UUOrderDetailVC.h"
#import "UUOrderAssignVC.h"
#import "UUResourceManager.h"

@interface UUOrderStateListVC () <UITableViewDataSource, UITableViewDelegate, UUOrderManagerObserver>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *emptyImageView;

@property (nonatomic, assign) UUOrderStatus status;
@property (nonatomic, strong) NSMutableArray<id> *orders;

@end

@implementation UUOrderStateListVC

+ (instancetype)orderStateListVCWithStatus:(UUOrderStatus)status {
    UUOrderStateListVC *listVC = [self instanceOfAppropriate];
    listVC.status = status;
    
    listVC.hidesBottomBarWhenPushed = YES;
    
    NSString *title = nil;
    switch (status) {
        case UUOrderStatusInService:
            title = @"服务中";
            break;
        case UUOrderStatusWaitingForAssign:
            title = @"待分配";
            break;
        case UUOrderStatusWaitingForService:
            title = @"待服务";
            break;
        case UUOrderStatusWaitingForConfirm:
            title = @"待确认";
            break;
        case UUOrderStatusNone:
            title = @"全部";
            break;
        default:
            DKAssert(0);
    }
    listVC.title = title;
    
    return listVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = COMMON_BACKGROUND_COLOR;
    self.tableView.rowHeight = 106;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"UUOrderCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    
    if (self.parentViewController != self.navigationController) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
    }];
    
    [self reload];
    
    [GetOrderManager() addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)reload {
    self.orders = [[GetOrderManager() fetchOrdersForStatus:self.status] mutableCopy];
    [self.tableView reloadData];
    
    if (self.status == UUOrderStatusNone && self.orders.count > 0) {
        WEAK_SELF();
        UURefreshFooter *footer = [UURefreshFooter footerWithRefreshingBlock:^{
            [weakSelf asyncFetchHistory];
        }];
        self.tableView.mj_footer = footer;
    } else {
        self.tableView.mj_footer = nil;
    }
    
    if (self.orders.count == 0) {
        if (self.emptyImageView == nil) {
            self.emptyImageView = [[UIImageView alloc] initWithImage:GetResourceManager().emptyDataImage];
            [self.view addSubview:self.emptyImageView];
            [self.emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(0);
                make.top.mas_equalTo(100);
            }];
        }
        
        self.emptyImageView.hidden = NO;
        self.tableView.hidden = YES;
    } else {
        self.emptyImageView.hidden = YES;
        self.tableView.hidden = NO;
    }
}

- (void)asyncFetchHistory {
    WEAK_SELF();
    [GetOrderManager() asyncFetchOrderHistoryListForOrderId:self.orders.lastObject length:20 completeBlock:^(NSArray<id> *orders, NSError *error) {
        if (error == nil) {
            if (orders.count < 20) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            [weakSelf.orders addObjectsFromArray:orders];
            
            NSMutableArray<NSIndexPath *> *insertRows = [NSMutableArray arrayWithCapacity:orders.count];
            for (NSUInteger i = weakSelf.orders.count - orders.count; i < weakSelf.orders.count; i++) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
                [insertRows addObject:indexPath];
            }

            [weakSelf.tableView insertRowsAtIndexPaths:insertRows
                                      withRowAnimation:UITableViewRowAnimationAutomatic];
        } else {
            [weakSelf.tableView.mj_footer endRefreshing];
        }
    }];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.orders.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    id orderId = self.orders[indexPath.row];
    UUOrderModel *order = [GetOrderManager() fetchOrderWithOrderId:orderId];
    
    [cell setupWithModel:order];
    
    WEAK_SELF();
    [cell setConfirmOrderBlock:^{
        ShowIndicatorInView(weakSelf.view);
        [GetOrderManager() asyncConfirmOrderWithOrderId:orderId confirm:YES completeBlock:^(NSError *error) {
            HideTipsOnView(weakSelf.view);
            
            if (error == nil) {
                ShowTipsOnView(@"确认成功", weakSelf.view);
            } else {
                ShowTipsOnView(error.localizedDescription, weakSelf.view);
            }
        }];
    }];
    
    [cell setAssignOrderBlock:^{
        UUOrderAssignVC *assignVC = [UUOrderAssignVC instanceOfAppropriate];
        assignVC.orderId = orderId;
        [weakSelf.navigationController pushViewController:assignVC animated:YES];
    }];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    id orderId = self.orders[indexPath.row];
    
    UUOrderDetailVC *detailVC = [UUOrderDetailVC instanceOfAppropriate];
    detailVC.orderId = orderId;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - UUOrderManagerObserver methods

- (void)orderManagerDidUpdateOrders:(NSArray<id> *)orders {
    [self reload];
}

@end
